#include "T_ModuleGroupRectItem.h"
#include <QPainter>
#include <QDebug>
#include <QGraphicsScene>
#include <QInputDialog>
#include <QCursor>
#include "T_CustomRectItem.h"
#include "marsspace.h"
#include "crectandpos.h"

bool g_allow_swap_wh = false; //切换水平垂直是不允许交换宽高

T_ModuleGroupRectItem::T_ModuleGroupRectItem(QObject *parent)
    : QObject(parent)
{
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
    setAcceptHoverEvents(true);
    setPen(QPen(Qt::darkBlue, 2));
}

void T_ModuleGroupRectItem::SetItemInfo(cutomitem data)
{
    QString tmp_name = data.name.split("_").first();
    
    int num = 1;
    for(auto name : g_item_group_names) {
        if(name.contains(tmp_name)) {
            num += 1;
        }
    }
    data.name = QString("%1_%2").arg(tmp_name).arg(num);   

    g_item_group_names.append(data.name);

    m_item_data = data;
    QColor brush_color(data.color);
    brush_color.setAlpha(120);
    setBrush(brush_color);

    // 设置布局属性
    updateLayout();         // 刷新布局
}

void T_ModuleGroupRectItem::setSpacing(double space)
{
    if(m_spacing != space){
        m_spacing = space;
        updateLayout();
    }
}

void T_ModuleGroupRectItem::setLayoutDirection(LayoutDirection direction)
{
    if(m_direction != direction){
        m_direction = direction;
        m_flag_realse = true;
        updateLayout();
    }
}

void T_ModuleGroupRectItem::addRectangle(QGraphicsRectItem *rectItem)
{
    if(!m_children.contains(rectItem)){
        rectItem->setParentItem(this);
        m_children.append(rectItem);
        updateLayout();
    }
}

void T_ModuleGroupRectItem::removeRectangle(QGraphicsRectItem *rectItem)
{
    if(m_children.removeOne(rectItem)){
        rectItem->setParentItem(nullptr);
        updateLayout();
    }
}

void T_ModuleGroupRectItem::updateLayout()
{
    prepareGeometryChange();

    qreal x = 0.0, y = 0.0;
    qreal maxWidth = 0.0, maxHeight = 0.0;

    for (auto child : m_children) {
        QRectF childRect = child->rect();

        if (g_allow_swap_wh && m_flag_realse) {
            // 仅交换宽高，保持本地坐标为(0,0)
            qreal originalWidth = childRect.width();
            qreal originalHeight = childRect.height();
            child->setRect(0, 0, originalHeight, originalWidth);
            childRect = child->rect(); // 获取新尺寸
        }

        // 统一设置位置
        child->setPos(x, y);

        // 计算下一个位置
        if (m_direction == Horizontal) {
            x += childRect.width() + m_spacing;
            maxHeight = qMax(maxHeight, childRect.height());
        } else if(m_direction == Vertical) {
            y += childRect.height() + m_spacing;
            maxWidth = qMax(maxWidth, childRect.width());
        } else if(m_direction == DD) {

        }
    }

    calculateGroupSize();
    //通知更新mainRect
    emit flushMainRect();
}

QString T_ModuleGroupRectItem::getItemName()
{
    return m_item_data.name;
}

cutomitem T_ModuleGroupRectItem::getItemData()
{
    return m_item_data;
}

qreal T_ModuleGroupRectItem::getMars(LayoutDirectionHV direction)
{
    switch (direction)
    {
    case Left_Top:
        return m_mar_spacing_top;
    case Left_Bottom:
        return m_mar_spacing_left;
    case Right_Top:
        return m_mar_spacing_right;
    case Right_Bottom:
        return m_mar_spacing_bottom;
    
    default:
        return qreal();;
    }
}

void T_ModuleGroupRectItem::setMars(qreal topMar, qreal leftMar, qreal bottomMar, qreal rightMar)
{
    m_mar_spacing_top = topMar;
    m_mar_spacing_left = leftMar;
    m_mar_spacing_bottom = bottomMar;
    m_mar_spacing_right = rightMar;

    updateLayout();
}

int T_ModuleGroupRectItem::getDirection()
{
    return m_direction;
}

qreal T_ModuleGroupRectItem::getSpacing()
{
    return m_spacing;
}

void T_ModuleGroupRectItem::calculateGroupSize()
{
    if(m_children.isEmpty()) return;

    QRectF totalRect;
    foreach(QGraphicsRectItem *child, m_children){
        QRectF itemRect = child->mapRectToParent(child->rect());
        totalRect = totalRect.united(itemRect);
    }

    // 调整容器矩形
    setRect(totalRect.adjusted(-m_mar_spacing_left, -m_mar_spacing_top, m_mar_spacing_right, m_mar_spacing_bottom)); // 添加边距,默认5像素
}

void T_ModuleGroupRectItem::deleteItems()
{
    T_CustomRectItem* m_main_rect = static_cast<T_CustomRectItem*>(this->parentItem());
    T_ModuleGroupRectItem *rect = this;
    disconnect(rect, &T_ModuleGroupRectItem::flushMainRect,m_main_rect,&T_CustomRectItem::updateLayout);
    disconnect(m_main_rect, &T_CustomRectItem::flushBlockLayout, rect, &T_ModuleGroupRectItem::updateLayout);

    m_main_rect->removeChild(rect);
    scene()->removeItem(rect);
    delete rect;
    rect = nullptr;
}

void T_ModuleGroupRectItem::calaOldRects()
{
    m_originalContainerRect = this->rect();
    m_originalChildPositions.clear();
    m_originalChildRects.clear();
    for (auto child : m_children) {
        m_originalChildPositions[child] = child->pos();
        m_originalChildRects[child] = child->rect();
    }
    m_originalSpacing = m_spacing;
    m_isFirstResize = false;
}

void T_ModuleGroupRectItem::calcZoomRects(const QRectF &newRect)
{
    if (newRect.width() > 0 && newRect.height() > 0)
    {
        setRect(newRect);

        //新增
        // 计算缩放比例
        const qreal scaleX = newRect.width() / m_originalContainerRect.width();
        const qreal scaleY = newRect.height() / m_originalContainerRect.height();

        // 缩放子项
        for (auto child : m_children) {
            const QPointF newPos(
                m_originalChildPositions[child].x() * scaleX,
                m_originalChildPositions[child].y() * scaleY
            );
            const QRectF newChildRect(
                0, 0,
                m_originalChildRects[child].width() * scaleX,
                m_originalChildRects[child].height() * scaleY
            );
            child->setPos(newPos);
            child->setRect(newChildRect);
        }
    }
}

void T_ModuleGroupRectItem::drawGuideLines(QPainter *painter)
{
    painter->save();
    // 绘制辅助线
    QPen guidePen(Qt::DashLine);
    guidePen.setColor(Qt::green);
    guidePen.setWidth(1);
    painter->setPen(guidePen);

    // 绘制水平和垂直辅助线
    int yp = boundingRect().top();
    int yb = boundingRect().bottom();
    int xp = boundingRect().left();
    int xb = boundingRect().right();

    painter->drawLine(xb, yp, xb + GuideLineNum, yp); 
    painter->drawLine(xp, yp, xb - GuideLineNum, yp); 
    painter->drawLine(xb, yb, xb + GuideLineNum, yb);
    painter->drawLine(xp, yb, xb - GuideLineNum, yb);
    painter->drawLine(xp, yp, xp, yp - GuideLineNum);
    painter->drawLine(xp, yb, xp, yb + GuideLineNum);
    painter->drawLine(xb, yp, xb, yp - GuideLineNum);
    painter->drawLine(xb, yb, xb, yb + GuideLineNum);

    painter->restore();
}

void T_ModuleGroupRectItem::drawTipLines(QPainter *painter)
{
    painter->save();
    //绘制线条标注
    painter->setPen(Qt::red);
    //绘制水平线
    int rect_center_x = (rect().topLeft().x() + rect().topRight().x())/2;
    int rect_center_y = rect().top();
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y() - 5,
                        rect_center_x - 20,rect_center_y - 5);
    painter->drawLine(rect_center_x + 20,rect_center_y - 5,
                        rect().topRight().x(),rect().topRight().y() - 5);
    //绘制竖直线条
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y(),rect().topLeft().x(),rect().topLeft().y() - 10);
    painter->drawLine(rect().topRight().x(),rect().topRight().y(),rect().topRight().x(),rect().topRight().y() - 10);
    //中间绘制宽度
    painter->drawText(rect_center_x - 10,rect_center_y-7,QString::number(rect().width(),'f',2));

    //绘制垂直线条
    int center_y_x = rect().left();
    int center_y_y = (rect().topLeft().y() + rect().bottomLeft().y()) / 2;;
    painter->drawLine(rect().topLeft().x() - 5,rect().topLeft().y(),center_y_x - 5,center_y_y - 20);
    painter->drawLine(center_y_x - 5,center_y_y + 20,rect().bottomLeft().x() - 5,rect().bottomLeft().y());
    //绘制水平小线条
    painter->drawLine(rect().topLeft().x(),rect().topLeft().y(),rect().topLeft().x()-10,rect().topLeft().y());
    painter->drawLine(rect().bottomLeft().x(),rect().bottomLeft().y(),rect().bottomLeft().x()-10,rect().bottomLeft().y());

    //计算文本中心点
    QRect textRect = painter->fontMetrics().boundingRect(center_y_x, center_y_y, 10, 10, Qt::AlignCenter, QString::number(rect().height(), 'f', 1));
    QPoint textCenter = QPoint(textRect.center().x(), textRect.center().y());
    // 以文本的中心为旋转中心
    painter->translate(textCenter.x(), textCenter.y());
    painter->rotate(-90);
    painter->translate(-textCenter.x(), -textCenter.y());
    painter->drawText(textCenter.x()-10, textCenter.y()-8,QString::number(rect().height(),'f',2));

    painter->restore();
}

void T_ModuleGroupRectItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    return;
    if((event->buttons() & Qt::LeftButton) == 0){
        return;
    }
    m_is_tip = true;

    if(m_resizeDirection == Inner) {
        // 新增：检测Ctrl键状态
        m_isCopying = event->modifiers() & Qt::ControlModifier;
        if(m_isCopying) {
            m_mousePressPos = event->scenePos(); // 保存原始位置
        }
    }

    m_isDragging = (m_resizeDirection != None && m_resizeDirection != Inner);
    m_lastMousePos = event->pos();
    m_lastPos = pos();

    //新增
    // 在开始拖动时记录初始状态
    if (m_isDragging) {
        calaOldRects();
    }

    QGraphicsRectItem::mousePressEvent(event);
}

void T_ModuleGroupRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    return;
    if((event->buttons() & Qt::LeftButton) == 0){
        return;
    }
    m_is_tip = true;

    // if(m_isDragging)
    // {
    //     QPointF delta = event->pos() - m_lastMousePos;
    //     QRectF newRect = rect();

    //     switch (m_resizeDirection)
    //     {
    //     case Left:
    //         newRect.setLeft(newRect.left() + delta.x());
    //         break;
    //     case Right:
    //         newRect.setRight(newRect.right() + delta.x());
    //         break;
    //     case Top:
    //         newRect.setTop(newRect.top() + delta.y());
    //         break;
    //     case Bottom:
    //         newRect.setBottom(newRect.bottom() + delta.y());
    //         break;
    //     case TopLeft:
    //         newRect.setTopLeft(newRect.topLeft() + delta);
    //         break;
    //     case TopRight:
    //         newRect.setTopRight(newRect.topRight() + delta);
    //         break;
    //     case BottomLeft:
    //         newRect.setBottomLeft(newRect.bottomLeft() + delta);
    //         break;
    //     case BottomRight:
    //         newRect.setBottomRight(newRect.bottomRight() + delta);
    //         break;
    //     default:
    //         break;
    //     }

    //     // 确保矩形大小不为负
    //     calcZoomRects(newRect);
    //     m_lastMousePos = event->pos();
    // }
    // else
    if (m_isCopying) {
        if (!m_copyItem) {
            // 创建临时复制体
            m_copyItem = createCopy();
            scene()->addItem(m_copyItem);

            // 显示辅助线
            m_showGuideLines = true;
        }

        // 更新复制体位置
        QPointF newPos = event->scenePos() - m_mousePressPos;
        QPointF tmp_pos = m_copyItem->mapFromScene(newPos);
        m_copyItem->setPos(tmp_pos);

        // 绘制辅助线
        scene()->update(scene()->sceneRect());
    }
    else
    {
        QGraphicsRectItem::mouseMoveEvent(event);

        QPointF newPos = pos();

        m_lastPos = newPos;
    }
}

void T_ModuleGroupRectItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    return;

    // if((event->buttons() & Qt::LeftButton) == 0){
    //     return;
    // }
    m_is_tip = true;
    m_isDragging = false;
    m_resizeDirection = None;

    // 新增复制逻辑
    if(m_isCopying && event->button() == Qt::LeftButton) {
        if (m_copyItem) {
            // 确保复制体在场景中
            if (!scene()->items().contains(m_copyItem)) {
                scene()->addItem(m_copyItem);
            }
            m_copyItem = nullptr; // 清理临时复制体
        }

        // 隐藏辅助线
        m_showGuideLines = false;
        m_isCopying = false;
    }

    //鼠标释放的时候更新布局
    m_flag_realse = false;
    updateLayout();

    QGraphicsRectItem::mouseReleaseEvent(event);
}

void T_ModuleGroupRectItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    return;

    const qreal handleSize = 5;
    QRectF rect = this->rect();
    QPointF pos = event->pos();

    if (qAbs(pos.x() - rect.left()) < handleSize && qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = TopLeft;
    } else if (qAbs(pos.x() - rect.right()) < handleSize && qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = TopRight;
    } else if (qAbs(pos.x() - rect.left()) < handleSize && qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = BottomLeft;
    } else if (qAbs(pos.x() - rect.right()) < handleSize && qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = BottomRight;
    } else if (qAbs(pos.x() - rect.left()) < handleSize) {
        m_resizeDirection = Left;
    } else if (qAbs(pos.x() - rect.right()) < handleSize) {
        m_resizeDirection = Right;
    } else if (qAbs(pos.y() - rect.top()) < handleSize) {
        m_resizeDirection = Top;
    } else if (qAbs(pos.y() - rect.bottom()) < handleSize) {
        m_resizeDirection = Bottom;
    } else if (rect.contains(pos.x(),pos.y())) {
        m_resizeDirection = Inner;
    }else {
        m_resizeDirection = None;
    }

    setCursorShape();
    QGraphicsRectItem::hoverMoveEvent(event);
}

void T_ModuleGroupRectItem::paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option,
                       QWidget *widget)
{
    painter->save();

    painter->setBrush(brush());
    painter->setPen(pen());
    painter->drawRect(rect());

    // //绘制文本
    // painter->setPen(Qt::black);
    // QStringList tmp_list = m_item_data.name.split("_");
    // if(tmp_list.size() >= 2)
    //     painter->drawText(rect().center().x()-10,rect().bottomLeft().y()+15,tmp_list[1]);

    painter->restore();

    // //绘制复制辅助线
    // if (m_showGuideLines && m_copyItem) {
    //     drawGuideLines(painter);
    // }

    // //绘制数据标注线
    // if(g_is_tip_line && m_is_tip) {
    //     drawTipLines(painter);
    // }
}

void T_ModuleGroupRectItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    return;

    QMenu menu;
    QAction *horzAct = menu.addAction("水平布局");
    QAction *vertAct = menu.addAction("垂直布局");
    QAction *spacingAct = menu.addAction("设置间距...");
    QAction *spaceAct = menu.addAction("设置边距");
    QAction *crectouterAct = menu.addAction("改变外部大小位置");
    QAction *crectinnerAct = menu.addAction("改变内部大小");
    QAction *deleteAct = menu.addAction("删除");

    QAction *selected = menu.exec(event->screenPos());
    if(selected == horzAct){
        setLayoutDirection(Horizontal);
    } else if(selected == vertAct){
        setLayoutDirection(Vertical);
    } else if(selected == spacingAct){
        bool ok;
        double newSpace = QInputDialog::getDouble(nullptr, "设置间距",
                                           "请输入间距值(像素):",
                                           m_spacing, 0, 100, 2, &ok);
        if(ok) setSpacing(newSpace);
    } else if(selected == deleteAct) {
        deleteItems();
    } else if(selected == spaceAct) {
        MarsSpaceIns->SetCurrentData(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
        int ret = MarsSpaceIns->exec();
        if(ret) {
            MarsSpaceIns->ChangeCurrentData(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
            setMarSpacing(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);
        }
    } else if(selected == crectouterAct) {
        CRectAndPosIns->SetCurrentData(rect());
        int ret = CRectAndPosIns->exec();
        if(ret) {
            QRectF tmprect = rect();
            CRectAndPosIns->ChangeCurrentData(tmprect);
            setNewOuterRectF(tmprect);
        }
    } else if(selected == crectinnerAct) {
        if(m_children.isEmpty()) {
            return;
        }
        qreal width = m_children[0]->rect().width();
        qreal height = m_children[0]->rect().height();
        CRectAndPosIns->SetCurrentData2(width,height);
        int ret = CRectAndPosIns->exec();
        if(ret) {
            CRectAndPosIns->ChangeCurrentData2(width,height);
            setNewInnerRect(width,height);
        }
    }
}

T_ModuleGroupRectItem *T_ModuleGroupRectItem::createCopy() const
{
    T_CustomRectItem* m_main_rect = static_cast<T_CustomRectItem*>(this->parentItem());

    T_ModuleGroupRectItem* copy = new T_ModuleGroupRectItem();
    connect(copy, &T_ModuleGroupRectItem::flushMainRect,m_main_rect,&T_CustomRectItem::updateLayout);

    // 为 m_main_rect 连接信号和槽，触发 group 的 updateLayout
    connect(m_main_rect, &T_CustomRectItem::flushBlockLayout, copy, &T_ModuleGroupRectItem::updateLayout);

    // 复制基本属性
    copy->SetItemInfo(m_item_data);
    QPointF tmp_pos = copy->mapFromScene(m_mousePressPos);
    copy->setRect(tmp_pos.x(),tmp_pos.y(),rect().x(),rect().y());
    copy->setSpacing(m_spacing);
    copy->setLayoutDirection(m_direction);
    copy->setPen(pen());
    copy->setBrush(brush());
    copy->setMarSpacing(m_mar_spacing_left,m_mar_spacing_top,m_mar_spacing_right,m_mar_spacing_bottom);

    // 复制子项
    foreach(QGraphicsRectItem* child, m_children) {
        QGraphicsRectItem* childCopy = new QGraphicsRectItem();
        // 复制子项属性
        childCopy->setRect(child->rect());
        childCopy->setPos(child->pos());
        childCopy->setPen(child->pen());
        childCopy->setBrush(child->brush());

        copy->addRectangle(childCopy);
    }

    m_main_rect->addChild(copy);
    
    return copy;
}

void T_ModuleGroupRectItem::setCursorShape()
{
    switch (m_resizeDirection) {
    case TopLeft:
    case BottomRight:
        setCursor(Qt::SizeFDiagCursor);
        break;
    case TopRight:
    case BottomLeft:
        setCursor(Qt::SizeBDiagCursor);
        break;
    case Left:
    case Right:
        setCursor(Qt::SizeHorCursor);
        break;
    case Top:
    case Bottom:
        setCursor(Qt::SizeVerCursor);
        break;
    case Inner:
        setCursor(Qt::CrossCursor);
        break;
    default:
        setCursor(Qt::ArrowCursor);
        break;
    }
}

void T_ModuleGroupRectItem::setMarSpacing(qreal space_left, qreal space_top, qreal space_right, qreal space_bottom)
{
    if(m_mar_spacing_left != space_left) {
        m_mar_spacing_left = space_left;
    }

    if(m_mar_spacing_top != space_top) {
        m_mar_spacing_top = space_top;
    }

    if(m_mar_spacing_right != space_right) {
        m_mar_spacing_right = space_right;
    }

    if(m_mar_spacing_bottom != space_bottom) {
        m_mar_spacing_bottom = space_bottom;
    }

    updateLayout();
}

void T_ModuleGroupRectItem::setNewOuterRectF(const QRectF &rectf)
{
    calaOldRects();
    calcZoomRects(rectf);
    setPos(mapFromParent(rectf.x(),rectf.y()));

    updateLayout();
}

void T_ModuleGroupRectItem::setNewInnerRect(qreal width, qreal height)
{
    for (auto child : m_children) {
        const QPointF newPos(child->x(),child->y());
        const QRectF newChildRect(0,0,width,height);
        child->setPos(newPos);
        child->setRect(newChildRect);
    }

    updateLayout();
}
